package com.maq.web;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.maq.base.utils.ResultUtil;
import com.maq.domain.vo.supper.PeopleBase;
import com.maq.service.PeopleBaseService;

@Controller
@RequestMapping("userAccount")
public class AccountController {

	@Autowired
	private PeopleBaseService peopleBaseService;

	@RequestMapping("loginPage")
	public String loginPage() {
		return "userAccount/login";
	}

	@RequestMapping("regist")
	public void regist(PeopleBase peopleBase, String registValidateCode, HttpServletRequest request,
			HttpServletResponse response) {
		String validateCode = ((String) request.getSession().getAttribute("VALIDATE_CODE")).toLowerCase();
		if (!validateCode.equals(registValidateCode.toLowerCase())) {
			ResultUtil.sendString(response, "验证码错误");
		} else {
			PeopleBase pb = peopleBaseService.findByEmailOrPhone(peopleBase);
			if (pb != null) {
				ResultUtil.sendString(response, "该邮箱帐号已存在");
			} else {
				peopleBaseService.save(peopleBase);
				pb = peopleBaseService.findByEmailOrPhone(peopleBase);
				request.getSession().setAttribute("User", pb);
				ResultUtil.sendString(response, "注册成功");
			}
		}
	}

	/**
	 * @return
	 */
	@ResponseBody
	@RequestMapping("loginCheck")
	public void loginCheck(PeopleBase peopleBase, String loginValidateCode, HttpServletRequest request,
			HttpServletResponse response) {
		String validateCode = ((String) request.getSession().getAttribute("VALIDATE_CODE")).toLowerCase();
		if (!validateCode.equals(loginValidateCode.toLowerCase())) {
			ResultUtil.sendString(response, "验证码错误");
		} else {
			PeopleBase pb = peopleBaseService.findByEmailOrPhone(peopleBase);
			if (pb == null) {
				ResultUtil.sendString(response, "该帐号不存在");
			} else if (!pb.getPassword().equals(peopleBase.getPassword())) {
				ResultUtil.sendString(response, "密码错误");
			} else {
				request.getSession().setAttribute("User", pb);
				ResultUtil.sendString(response, "登录成功");
			}
		}
	}

	@RequestMapping("validateCode")
	public void ValidateCode(HttpServletRequest req, HttpServletResponse resp) {
		// 构造Random对象（用于产生验证码文字和颜色）
		Random random = new Random();

		// 设置浏览器不缓存页面
		resp.setHeader("Pragma", "No-cache");
		resp.setHeader("Cache-Control", "no-cache");
		resp.setDateHeader("Expires", 0);

		char[] codeSequence = "0123456789".toCharArray();

		// 生成4位随机验证码
		String code = "";
		for (int i = 0; i < 4; i++) {
			code += String.valueOf(codeSequence[random.nextInt(10)]);
		}

		// 将验证码存入session
		req.getSession().setAttribute("VALIDATE_CODE", code);

		int w = 100; // 图片宽度和高度
		int h = 40;
		// 在内存中创建图片对象
		BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

		// 获取并设置图形上下文
		Graphics g = image.getGraphics();
		g.setColor(getRandomColor(50, 250));// 设置背景颜色
		g.fillRect(0, 0, w, h); // 绘制矩形区域

		// 绘制100条随机干扰线
		for (int i = 0; i < 100; i++) {
			g.setColor(getRandomColor(200, 250));
			int x1 = random.nextInt(w);
			int y1 = random.nextInt(h);
			int x2 = random.nextInt(16); // 干扰线宽高
			int y2 = random.nextInt(16);
			g.drawLine(x1, y1, x1 + x2, y1 + y2);
		}

		g.setFont(new Font("serif", Font.CENTER_BASELINE, 32));// 设置字体
		for (int i = 0; i < 4; i++) {
			String s = code.substring(i, i + 1); // 得到当前字符
			g.setColor(getRandomColor(200, 250));// 设置当前字符颜色
			g.drawString(s, 24 * i + 6, 30); // 绘制当前字符
		}

		g.dispose(); // 销毁图形上下文

		// 将图片写到页面
		try {
			ImageIO.write(image, "JPEG", resp.getOutputStream());
		} catch (Exception e) {
		}
	}

	/**
	 * @Title: getRandomColor
	 * @Description: 得到范围内的随机颜色
	 * @param begin
	 *            范围开始值
	 * @param end
	 *            范围结束值
	 * @return 返回类型 :Color 随机得到的颜色
	 */
	private Color getRandomColor(int begin, int end) {
		Random random = new Random();
		int range = end - begin;
		int r = begin + random.nextInt(range);
		int g = begin + random.nextInt(range);
		int b = begin + random.nextInt(range);
		return new Color(r, g, b);
	}

}
